package fr.emse.tatiana.replayable;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;


public class TraceReplayer implements DiscreteReplayable, ExternalReplayable {
	
	XmlRpcClient replayer;
	private String programname;
	private Long starttime;
	private Long endtime;
	//TODO z later handle delta
	
	public TraceReplayer(String programname, long starttime, long endtime) {
		this.programname = programname;
		this.starttime = starttime;
		this.endtime = endtime;
		int port=8080;
		if ("coffee".equalsIgnoreCase(programname)) {
			port=65003;
		}
		
	    XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
	    try {
			config.setServerURL(new URL("http://127.0.0.1:"+port+"/tatiana"));
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
	    replayer = new XmlRpcClient();
	    replayer.setConfig(config);
	    
	}
	
	public void goTo(SynchronisationEvent extract) {
		
		if (extract.getNow()==null) {
			return;
		}
		long time = extract.getNow();
		
		// check if we are in range or not
		if (time<starttime) {
			time = starttime;
		} else if (time>endtime ) {
			time = endtime;
		}
		System.err.println("TraceReplayer : sending "+time);
	    Object[] params = new Object[]{""+time};
	    try {
			replayer.execute("Replayer.goTo", params);
		} catch (XmlRpcException e1) {
			e1.printStackTrace();
		}
	}

	public void mark(long time) {
	    Object[] params = new Object[]{""+time};
	    try {
			replayer.execute("Replayer.mark", params);
		} catch (XmlRpcException e1) {
			e1.printStackTrace();
		}	
	}

	public void openFile(String filename) throws XmlRpcException {
	    Object[] params = new Object[]{filename};
		replayer.execute("Replayer.openFile", params);
	}

	public List<Long> getEvents() {
		List<Long> ret = new ArrayList<Long>();
	    Object[] params = new Object[]{};
	    try {
			Object[] execute = (Object[]) replayer.execute("Replayer.getEvents", params);
			for(int i=0; i<execute.length; i++) {
				ret.add(Long.valueOf((String) execute[i]));
			}
		} catch (XmlRpcException e1) {
			// do nothing
			e1.printStackTrace();
		}
		return ret;
	}

	public void end() {
		
	    Object[] params = new Object[]{};
	    try {
			replayer.execute("Replayer.end", params);
		} catch (XmlRpcException e1) {
			System.err.println("Replayer ended");
		}
	}

	public String getName() {
		return programname;
	}

}
